package com.up.selfshop.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.up.selfshop.config.MyConfig;

/**
 * 
 * @author liuzy
 * @since 2016年8月30日
 */
public class MyFilter implements Filter {
	private Logger logger = Logger.getLogger(MyFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		req.setCharacterEncoding("UTF-8");
		res.setCharacterEncoding("UTF-8");
		logReq(req);
		req.setAttribute("ProjectName", MyConfig.get("ProjectName"));
		chain.doFilter(req, res);
	}

	@Override
	public void destroy() {
	}

	public void logReq(HttpServletRequest req) {
		String path = req.getPathInfo();
		if (!isStatic(path)) {
			StringBuilder sb = new StringBuilder();
			sb.append(" ");
			sb.append(req.getMethod());
			sb.append(" ");
			sb.append(path == null ? "/" : path);
			String query = req.getQueryString();
			sb.append(query == null || query.isEmpty() ? "" : ("&" + query));
			logger.info(sb);
		}
	}

	public static final String[] STATIC_SUFFIX = { ".js", ".map", ".css", "ico", ".jpg", ".png", ".gif", ".eot", ".ttf", ".woff", ".woff2", ".apk" };

	public boolean isStatic(String path) {
		for (String suffix : STATIC_SUFFIX) {
			if (path == null || path.toLowerCase().endsWith(suffix)) {
				return true;
			}
		}
		return false;
	}

}
